6. Multer for file upload
Multer is a middleware for handling multipart/form-data, primarily used for uploading files in Node.js and Express applications.
It processes incoming form data and allows files to be uploaded and saved locally or in memory.
1. Installing Multer
npm install multer
2. File Upload with Multer
src/middleware/multer middleware.js
import multer from 'multer';
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/temp')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.originalname)
}
})
export const upload = multer({ storage, })
- It creates a storage system that saves uploaded files to a folder called "temp" inside the "public" directory.
- When a file is uploaded, it generates a unique filename by using the current date and time, and a random number.
- However, instead of using the unique filename, it actually uses the original filename of the uploaded file.
- The code then exports a variable called "upload" which is an instance of Multer, configured to use the storage system it just created.